import { h, ref } from 'vue';
import { NSwitch } from 'naive-ui';
import { cloneDeep } from 'lodash-es';
import { renderImage } from '@/utils';
import { Switch } from '@/api/addons/hgexample/epBanner';
import { usePermission } from '@/hooks/web/usePermission';

const { hasPermission } = usePermission();
const $message = window['$message'];

export class State {
  public id = 0; // ID
  public title = ''; // 标题
  public linkurl = ''; // 链接地址
  public bannerimage = ''; // 图片
  public sort = 0; // 排序
  public state = 2; // 状态
  public createdAt = ''; // 创建日期
  public updatedAt = ''; // 更新时间
  public deletedAt = ''; // 删除时间

  constructor(state?: Partial<State>) {
    if (state) {
      Object.assign(this, state);
    }
  }
}

export function newState(state: State | Record<string, any> | null): State {
  if (state !== null) {
    if (state instanceof State) {
      return cloneDeep(state);
    }
    return new State(state);
  }
  return new State();
}
export const schemas = {};
// 表单验证规则
export const rules = {
  title: {
    required: true,
    trigger: ['blur', 'input'],
    type: 'string',
    message: '请输入标题',
  },
  sort: {
    required: true,
    trigger: ['blur', 'input'],
    type: 'number',
    message: '请输入排序',
  },
};

// 表格搜索表单

// 表格列
export const columns = [
  {
    title: 'ID',
    key: 'id',
    align: 'left',
    width: -1,
  },
  {
    title: '标题',
    key: 'title',
    align: 'left',
    width: -1,
  },
  {
    title: '链接地址',
    key: 'linkurl',
    align: 'left',
    width: -1,
  },
  {
    title: '图片',
    key: 'bannerimage',
    align: 'left',
    width: -1,
    render(row: State) {
      return renderImage(row.bannerimage);
    },
  },
  {
    title: '排序',
    key: 'sort',
    align: 'left',
    width: -1,
  },
  {
    title: '状态',
    key: 'state',
    align: 'left',
    width: -1,
    render(row: State) {
      return h(NSwitch, {
        value: row.state === 1,
        checked: '开启',
        unchecked: '关闭',
        disabled: !hasPermission(['/hgexample/epBanner/switch']),
        onUpdateValue: function (e) {
          console.log('onUpdateValue e:' + JSON.stringify(e));
          row.state = e ? 1 : 2;
          Switch({ id: row.id, key: 'state', value: row.state }).then((_res) => {
            $message.success('操作成功');
          });
        },
      });
    },
  },
  {
    title: '创建日期',
    key: 'createdAt',
    align: 'left',
    width: -1,
  },
  {
    title: '更新时间',
    key: 'updatedAt',
    align: 'left',
    width: -1,
  },
];